import axios from 'axios'
import store from '@/store'
// 导入路由实例
import router from '@/router'
// baseURL 超时时间配置
const instance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front.itheima.net'
  // timeout: 5000
})

// 全局注入token
instance.interceptors.request.use(config => {
  // 获取token
  const { token } = store.state.user.profile
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

// 处理返回数据 token失效跳回到登录页
instance.interceptors.response.use(

  (response) => {
    return response.data
  },
  (error) => {
    // 处理401
    if (error.response && error.response.status === 401) {
      //  获取当前出现的401页面  vue3需要加value
      const currentPage = encodeURIComponent(router.currentRoute.value.fullPath)
      router.replace(`login?redirectUrl=${currentPage}`)
    }
    return Promise.reject(error)
  }
)
/**
 * 封装 axios.create创建的instance
 */
/**
 *
 * @param {*} url
 * @param {*} method => get/post
 * @param {*} params
 * @returns
 */
const request = (url, method, submitParams) => {
  return instance({
    url,
    method,
    // 区分是get(params)还是post(data)
    [method === 'get' ? 'params' : 'data']: submitParams
  })
}
export default request
